package com.example.myapplication.base.network.retrofit;



import com.example.myapplication.base.ApiException;
import com.example.myapplication.base.Data;
import com.google.gson.Gson;

import java.io.IOException;
import java.lang.reflect.Type;

import okhttp3.ResponseBody;
import retrofit2.Converter;


/**
 * 自定义Converter
 * 功能：
 * 先将返回的json数据解析到Response中，如果code==200，则解析到我们的实体基类中，否则抛异常
 */


public class GsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
    private final Gson gson;
    private final Type type;


    public GsonResponseBodyConverter(Gson gson, Type type) {
        this.gson = gson;
        this.type = type;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {

        String response = value.string();
        //先将返回的json数据解析到Response中，如果code==200，则解析到我们的实体基类中，否则抛异常

            Data httpResult = gson.fromJson(response, Data.class);
            if ("ok".equals(httpResult.getStatus()) || httpResult.getCode() == 0) {
                return gson.fromJson(response, type);
            } else {
                ApiException errorResponse = gson.fromJson(response, ApiException.class);
                //抛一个自定义ResultException 传入失败时候的状态码，和信息
                throw new ApiException(errorResponse.getMsg(), errorResponse.getStatus());
            }

    }
}
